package vip.xiaonuo.supplier.modular.base.categories.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.supplier.modular.structure.org.entity.SupplierOrg;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.supplier.modular.base.categories.entity.SupplierCategories;
import vip.xiaonuo.supplier.modular.base.categories.mapper.SupplierCategoriesMapper;
import vip.xiaonuo.supplier.modular.base.categories.param.SupplierCategoriesAddParam;
import vip.xiaonuo.supplier.modular.base.categories.param.SupplierCategoriesEditParam;
import vip.xiaonuo.supplier.modular.base.categories.param.SupplierCategoriesIdParam;
import vip.xiaonuo.supplier.modular.base.categories.param.SupplierCategoriesPageParam;
import vip.xiaonuo.supplier.modular.base.categories.service.SupplierCategoriesService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 商品分类Service接口实现类
 *
 * @author Mr.wu
 * @date  2024/10/22 17:18
 **/
@Service
public class SupplierCategoriesServiceImpl extends ServiceImpl<SupplierCategoriesMapper, SupplierCategories> implements SupplierCategoriesService {

    @Override
    public Page<SupplierCategories> page(SupplierCategoriesPageParam supplierCategoriesPageParam) {
        QueryWrapper<SupplierCategories> queryWrapper = new QueryWrapper<SupplierCategories>().checkSqlInjection();
        //数据归属
        queryWrapper.lambda().eq(SupplierCategories::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isNotEmpty(supplierCategoriesPageParam.getParentId())){
            List<String> childCategoriesIdList = CollStreamUtil.toList(this.getChildListById(this
                    .getAllCategoriesList(), supplierCategoriesPageParam.getParentId(), true), SupplierCategories::getId);
            if (ObjectUtil.isNotEmpty(childCategoriesIdList)) {
                queryWrapper.lambda().in(SupplierCategories::getParentId, childCategoriesIdList);
            } else {
                return new Page<>();
            }
        }
        if(ObjectUtil.isAllNotEmpty(supplierCategoriesPageParam.getSortField(), supplierCategoriesPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierCategoriesPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierCategoriesPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierCategoriesPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierCategories::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<Tree<String>> tree() {
        // 获取本单位所有分类
        List<SupplierCategories> allCategoriesList = this.list(new LambdaQueryWrapper<SupplierCategories>().eq(SupplierCategories::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        List<TreeNode<String>> treeNodeList = allCategoriesList.stream().map(supplierCategories ->
                        new TreeNode<>(supplierCategories.getId(), supplierCategories.getParentId(),
                                supplierCategories.getCategoriesName(), supplierCategories.getSortCode()).setExtra(JSONUtil.parseObj(supplierCategories)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierCategoriesAddParam supplierCategoriesAddParam) {
        //数据归属
        supplierCategoriesAddParam.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        SupplierCategories supplierCategories = BeanUtil.toBean(supplierCategoriesAddParam, SupplierCategories.class);
        this.save(supplierCategories);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierCategoriesEditParam supplierCategoriesEditParam) {
        SupplierCategories supplierCategories = this.queryEntity(supplierCategoriesEditParam.getId());
        BeanUtil.copyProperties(supplierCategoriesEditParam, supplierCategories);
        this.updateById(supplierCategories);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierCategoriesIdParam> supplierCategoriesIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(supplierCategoriesIdParamList, SupplierCategoriesIdParam::getId));
    }

    @Override
    public SupplierCategories detail(SupplierCategoriesIdParam supplierCategoriesIdParam) {
        return this.queryEntity(supplierCategoriesIdParam.getId());
    }

    @Override
    public SupplierCategories queryEntity(String id) {
        SupplierCategories supplierCategories = this.getById(id);
        if(ObjectUtil.isEmpty(supplierCategories)) {
            throw new CommonException("商品分类不存在，id值为：{}", id);
        }
        return supplierCategories;
    }

    @Override
    public List<SupplierCategories> getAllCategoriesList() {
        //Mr.wu 2024.9.20 添加数据归属隔离
        return this.list(new LambdaQueryWrapper<SupplierCategories>().eq(SupplierCategories::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()).orderByAsc(SupplierCategories::getSortCode));
    }

    @Override
    public List<Tree<String>> categoriesTreeSelector() {
        LambdaQueryWrapper<SupplierCategories> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //Mr.wu 2024-9-20 虽然下面的定义机构集合里已经有了数据归属隔离，在此再次添冗余，以防越界
        lambdaQueryWrapper.eq(SupplierCategories::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId());
        lambdaQueryWrapper.orderByAsc(SupplierCategories::getSortCode);
        List<SupplierCategories> supplierCategoriesList = this.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = supplierCategoriesList.stream().map(supplierCategories ->
                        new TreeNode<>(supplierCategories.getId(), supplierCategories.getParentId(), supplierCategories.getCategoriesName(), supplierCategories.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public List<SupplierCategories> getChildListById(List<SupplierCategories> categoriesDataList, String id, boolean includeSelf) {
        List<SupplierCategories> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(categoriesDataList, id, resultList);
        if(includeSelf) {
            SupplierCategories self = this.getById(categoriesDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    @Override
    public List<SupplierCategories> getParentListById(List<SupplierCategories> categoriesDataList, String id, boolean includeSelf) {
        List<SupplierCategories> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(categoriesDataList, id, resultList);
        if(includeSelf) {
            SupplierCategories self = this.getById(categoriesDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }
    @Override
    public SupplierCategories getById(List<SupplierCategories> categoriesDataList, String id) {
        int index = CollStreamUtil.toList(categoriesDataList, SupplierCategories::getId).indexOf(id);
        return index == -1?null:categoriesDataList.get(index);
    }

    public void execRecursionFindChild(List<SupplierCategories> categoriesDataList, String id, List<SupplierCategories> resultList) {
        categoriesDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(categoriesDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<SupplierCategories> categoriesDataList, String id, List<SupplierCategories> resultList) {
        categoriesDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                SupplierCategories parent = this.getById(categoriesDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(categoriesDataList, item.getParentId(), resultList);
            }
        });
    }


}
